﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace NetClient
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        Socket clientSocket = null;
        static Boolean isListen = true;
        Thread thDataFromServer;
        IPAddress ipadr;
        int Port;
        Byte[] bytesSend = new Byte[44];
        private void butOpen_Click(object sender, EventArgs e)
        {
            //每一个连接的客户端必须设置一个唯一的用户名，在服务器端是把用户名和套接字保存在Dictionary<userName,ClientSocket>中

            if (clientSocket == null || !clientSocket.Connected)
            {
                try
                {
                    clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    if (!String.IsNullOrWhiteSpace(txtIp.Text.ToString().Trim()))
                    {
                        try
                        {
                            ipadr = IPAddress.Parse(txtIp.Text.ToString().Trim());
                        }
                        catch
                        {
                            MessageBox.Show("请输入正确的IP后重试");
                            return;
                        }
                    }
                    else
                    {
                        MessageBox.Show("请输入正确的IP后重试");
                        return;
                    }
                    if (!String.IsNullOrWhiteSpace(txtPort.Text.ToString().Trim()))
                    {
                        try
                        {
                            Port = int.Parse(txtPort.Text.Trim());
                        }
                        catch
                        {
                            MessageBox.Show("请输入正确的端口后重试");
                            return;
                        }
                    }
                    else
                    {
                        MessageBox.Show("请输入正确的端口后重试");
                        return;
                    }
                    Port = int.Parse(txtPort.Text.Trim());
                    clientSocket.BeginConnect(ipadr, Port, (args) =>
                    {
                        if (args.IsCompleted)   //判断该异步操作是否执行完毕
                        {
                            Byte[] bytesSend = new Byte[44];
                            bytesSend = Encoding.UTF8.GetBytes("0044100001AFF00298VER1.30 2018/03/03        ");  //数据这里是刚刚连接上时需要传过去
                            if (clientSocket != null && clientSocket.Connected)
                            {
                                clientSocket.Send(bytesSend);
                                thDataFromServer = new Thread(DataFromServer);
                                thDataFromServer.IsBackground = true;
                                thDataFromServer.Start();
                                this.Invoke(new Action(() =>
                                {
                                    txtReceiveMsg.Text += Environment.NewLine + DateTime.Now.ToString() + "：" + System.Text.Encoding.UTF8.GetString(bytesSend);
                                }));
                            }
                            else
                            {
                                MessageBox.Show("服务器已关闭");
                            }
                        }
                    }, null);
                }
                catch (SocketException ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
            else
            {
                MessageBox.Show("你已经连接上服务器了");
            }

        }

        //获取服务器端的消息
        private void DataFromServer()
        {
            isListen = true;
            try
            {
                while (isListen)
                {
                    Byte[] bytesFrom = new Byte[4096];
                    Int32 len = clientSocket.Receive(bytesFrom);
                    String dataFromClient = Encoding.UTF8.GetString(bytesFrom, 0, len);
                    this.Invoke(new Action(() =>
                    {
                        txtSendMsg.Text += Environment.NewLine + DateTime.Now.ToString() + "：" + dataFromClient;
                    }));
                    //功能号/序列号/包内容
                    string func_no, serial_id, body;
                    func_no = dataFromClient.Substring(4, 2);
                    serial_id = dataFromClient.Substring(6, 4);
                    body = dataFromClient.Substring(10, dataFromClient.Length - 10);


                    string str = "05" + Get_id(serial_id) + "AFF00005VER1.30 2018/03/03        ";
                    int length = str.Length;
                    str = Get_id(length.ToString()) + str;
                    bytesSend = Encoding.UTF8.GetBytes(str);

                    if (func_no.Equals("10"))
                    {
                        string valid_flag = body.Substring(0, 1);
                        string Cur_time = body.Substring(1, 12);
                        this.Invoke(new Action(() =>
                        {
                            labCur_time.Text = "服务器时间：" + Get_time(Cur_time);
                        }));
                        
                        clientSocket.Send(bytesSend);
                        this.Invoke(new Action(() =>
                        {
                            txtReceiveMsg.Text += Environment.NewLine + DateTime.Now.ToString() + "：" + System.Text.Encoding.UTF8.GetString(bytesSend);
                        }));
                    }
                    else if (func_no.Equals("05"))
                    {
                        string Cur_time = body.Substring(0, 12);
                        this.Invoke(new Action(() =>
                        {
                            labCur_time.Text = "服务器时间："+Get_time(Cur_time);
                            timer1.Enabled = true;
                        }));

                    }
                }
            }
            catch (SocketException ex)
            {
            }
        }
        private static string Get_id(string serial_id)
        {
            string str;
            int id = int.Parse(serial_id);
            if (id >= 1000)
            {
                id++;
                str = id.ToString();
            }
            else if (id >= 100 && id < 1000)
            {
                id++;
                str = "0" + id.ToString();
            }
            else if (id >= 10 && id < 100)
            {
                id++;
                str = "00" + id.ToString();
            }
            else
            {
                id++;
                str = "000" + id.ToString();
            }
            return str;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            clientSocket.Send(bytesSend);
            this.Invoke(new Action(() =>
            {
                txtReceiveMsg.Text += Environment.NewLine + DateTime.Now.ToString() + "：" + System.Text.Encoding.UTF8.GetString(bytesSend);
            }));
        }

        private string Get_time(string time)
        {
            string str;
            str = "20" + time.Substring(0, 2)+"-"+time.Substring(2,2)+"-"+time.Substring(4,2)+" "+time.Substring(6,2)+":"+time.Substring(8,2)+":"+time.Substring(10,2);

            return str;
        }
    }
}
